﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using VideoView.Models;

namespace VideoView.Controllers
{
    public class HomeController : Controller
    {
        private DB.MyContext myContext;
        public HomeController(DB.MyContext p1)
        {
            myContext = p1;
        }

        public IActionResult Index()
        {
            SaveLog();
            return View();
        }

        public IActionResult Youku()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task<string> HeartCheck()
        {
            var form = await Request.ReadFormAsync();

            var videoTime = form["videoTime"];
            var videoLink = form["videoLink"];

            SaveLog(videoTime, videoLink);

            return "Ok";
        }

        private void SaveLog(string videoTime = "", string videoLink = "")
        {
            var userAgent = Request.Headers["User-Agent"].ToString();
            var _accessor = Core.ServiceLocator.Instance.CreateScope().ServiceProvider.GetService<IHttpContextAccessor>();
            var ipStr = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            var obj = new DB.Model.VideoLog
            {
                IP = ipStr,
                UserAgent = userAgent,
                AddDate = DateTime.Now,
                VideoLink = videoLink,
                VideoTime = videoTime
            };

            myContext.Add(obj);
            myContext.SaveChanges();
        }

        [HttpGet]
        public IActionResult Csy123456()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Csy123456(string aaa = "")
        {
            var data = Request.ReadFormAsync().Result;
            int page = int.Parse(data["page"]);// 1
            int rows = int.Parse(data["rows"]);// 30

            var query = myContext.VideoLogs.OrderByDescending(a => a.AddDate);

            var list = query.Skip((page - 1) * rows).Take(rows).ToList();

            return new JsonResult(new
            {
                rows = list,
                total = query.Count()
            });
        }
    }
}
